package com.walming.generator.copycat;

import com.walming.generator.copycat.annotaion.processor.time.TimeProcessorContainer;

import java.util.concurrent.atomic.AtomicBoolean;

/**
 * CopycatShutdownHook
 *
 * @author walming
 * @date 2020-09-29 16:14
 */
public class CopycatShutdownHook extends Thread {

    private final AtomicBoolean destroyed = new AtomicBoolean(false);

    static {
        try {
            Runtime.getRuntime().addShutdownHook(getInstance());
        } catch (Exception ignored) {

        }
    }

    private CopycatShutdownHook(final String name) {
        super(name);
    }

    private static class CopycatShutdownHookFactory {
        private static final CopycatShutdownHook INSTANCE = new CopycatShutdownHook("copycat-shutdown-hook");
    }

    /**
     * Gets CopycatShutdownHook instance.
     *
     * @return {@link CopycatShutdownHook}
     */
    public static CopycatShutdownHook getInstance() {
        return CopycatShutdownHookFactory.INSTANCE;
    }

    @Override
    public void run() {
        closeAll();
    }

    private void closeAll() {
        if (!destroyed.compareAndSet(false, true)) {
            return;
        }
        // 清理-缓存
        CriteriaAnnotationProcessorAdvisor.destroyProcessorCache();
        TimeProcessorContainer.destroyProcessorCache();
    }

}
